package org.jizp.web.utils;

import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import org.jizp.web.annotition.Controller;
import org.jizp.web.bean.XmlBean;

public class PackUtils {

	public static void addClassAndMethodByAnnotation(String packageName,
			Map<String, XmlBean> mvcMapping) throws Exception {
		List<Class<?>> classList = new ArrayList<Class<?>>();
		getClassList(packageName, classList, mvcMapping);
	}

	private static void getClassList(String packageName,
			List<Class<?>> classList , Map<String, XmlBean> mvcMapping) throws Exception {
		Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(packageName.replaceAll("\\.", "/"));
		while(urls.hasMoreElements()){
			URL url = urls.nextElement();
			if(url.getProtocol().equals("file")){
				String packagePath = url.getPath();
				addClass(packageName, packagePath, classList, mvcMapping);
			}
		}
	}

	private static void addClass(String packageName, String packagePath,
			List<Class<?>> classList, Map<String, XmlBean> mvcMapping) {
		try {
			File[] files = getClassFiles(packagePath);
			if (files != null) {
				for(File file : files){
					String fileName = file.getName();
					if(file.isFile()){
						String className = getClassName(packageName, fileName);
						Class<?> cls = Class.forName(className);
						if(cls.isAnnotationPresent(Controller.class)){
							Controller controller = cls.getAnnotation(Controller.class);
							String actionClassName = controller.value();
							XmlBean bean = new XmlBean();
							bean.setId(actionClassName);
							bean.setClassType(className);
							mvcMapping.put(actionClassName, bean);
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}

	private static String getClassName(String packageName, String fileName) {
		String className = fileName.substring(0, fileName.lastIndexOf("."));
		if(!packageName.equals("")){
			className = packageName + "." + className;
		}
		return className;
	}

	private static File[] getClassFiles(String packagePath) {
		
		return new File(packagePath).listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File file) {
				return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
			}
		});
	}

}
